// 使用goroutine和channel实现一个计算int64随机数各位数和的程序。
// 开启一个goroutine循环生成int64类型的随机数，发送到jobChan
// 开启24个goroutine从jobChan中取出随机数计算各位数的和，将结果发送到resultChan
// 主goroutine从resultChan取出结果并打印到终端输出

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"
)

type resultStruct struct {
	num    int64
	result int
}

// 随机数
func RandomNum(num chan<- int64) {
	for i := 0; i < 100; i++ {
		r := rand.New(rand.NewSource(99))
		r.Seed(time.Since(time.Now()).Nanoseconds())
		num <- r.Int63()
	}
	close(num)
}

// 取数据计算放入结果
func getResult(num <-chan int64, resultChan chan<- resultStruct) {
	var resultNum resultStruct
	for {
		select {
		case i := <-num:
			resultNum.num = i
			resultNum.result = NumStr(i)
			resultChan <- resultNum
		default:
			break
		}
	}
}

// 计算
func NumStr(a int64) int {
	var sum int
	for _, v := range strconv.Itoa(int(a)) {
		// fmt.Printf("%v  %v\n", sum, (int(v) - '0'))
		sum += (int(v) - '0')
	}
	return sum
}

func main() {
	var jobChan chan int64
	var resultChan chan resultStruct
	jobChan = make(chan int64)
	resultChan = make(chan resultStruct, 24)

	go RandomNum(jobChan)
	for i := 0; i < 24; i++ {
		go getResult(jobChan, resultChan)
	}

	for i := 0; i < 100; i++ {
		fmt.Println(<-resultChan)
	}
	close(resultChan)
	fmt.Println("------------------------------")

}
